#ifndef SENSORMANAGER_H
#define SENSORMANAGER_H

/**
 * @copyright Copyright (c) 2025 
 * CSG Digital Grid Technology (Guangdong) Co., Ltd.
 * @author zhouyan
*/
#include "inc/sys_inc.h"
#include "tools/auto_guard.h"
#include "tools/m_mutex.h"
#include "thirdparty/rapidjson/document.h"
#include "datacenter.h"
#include "idevice.h"

typedef std::map<std::string, DC::ModelItems> RegisterModels;

class RegBase;
class SensorNode;
class sensormanager : public DataCenter
{
    typedef std::list<SensorNode*> Sensors;
    typedef std::map<IDevice*, Sensors> mapSensors;
public:
    static sensormanager* getInstance();
    sensormanager();
    ~sensormanager();

    void startServer();
    void startReport();
    void startSMYL();

    bool loadSensors();
    bool clearSensors();
    bool checkModels(void);
    bool checkDevs(void);
    bool checkUartInfo(void);
    void BoardCastsendErrorInfo(const char *topic, const char *msg);

    static void copyDevInfo(DC::DevInfo &dc, const IDevice *dev);

    void getSensors(Sensors &sensors);
    SensorNode* findSensor(const char *dev_guid);
    bool onMsgArrvd(const char *topic, int topic_len, const char *msg, int msg_len);
protected:
    void onConnect();
    void onConnectionLost(const char *cause);

private:
    SensorNode * loadSensor(rapidjson::Value *js, int dev_type = 0);

    void sendData(IDevice *dev, const Sensors &sensors, bool force = false, bool reportType = false, std::string starttime = 0);
    void realTimeData(SensorNode *sensor);
    void responseRealTimeData(IDevice::Actions& action);

    SensorNode *findSensorByDevId(const char *dev_id);
    std::vector<SensorNode*> findSensorByDevAddr(const char *dev_addr);
    void BoardCastsendDevState(const SensorNode *sensor, std::string starttime, bool Type);
    void SendDevState(const SensorNode *sensor, bool Type);
    void sendYKData(
                const char* app,
                const char* token,
                const char *uid,
                const char* dev,
                const char* name,
                const char* type,
                const char* cmd,
                const char* action,
                const char* mode,
                const char* timeout,
                bool        Status);

    static void* serverThread(void *argv);
    void handle();

private:
    static sensormanager*   instanceM;
    static MMutex           instanceLockM;

    bool                    isReport;
    bool                    isSYMC;
    mapSensors              sensors_;
    std::list<IDevice *>    offline_devs_;
    bool                    needCheckDevs_;
    DC::DevInfos            registerDevInfos_;
    bool                    restartFlag_;
};

#endif // SENSORMANAGER_H
